package com.party.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.party.business.service.ITUserNoticeService;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.utils.StringUtils;
import com.party.course.domain.AmountInfo;
import com.party.course.service.IAmountInfoService;
import com.party.system.mapper.SysUserMapper;
import com.party.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {



    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITUserNoticeService userNoticeService;

    @Autowired
    private IAmountInfoService  amountInfoService;


    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        System.out.println("执行无参方法");
    }
    @Resource
    private SysUserMapper sysUserMapper;
    public void updateAmountStatus() {

        QueryWrapper<AmountInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("valid_status","0");
        // 查询已到达生效时间的记录（valid_time <= 当前时间）
        queryWrapper.le("valid_time", LocalDateTime.now());
        // 可以添加按照时间排序，提高查询效率
        queryWrapper.orderByAsc("valid_time");
        List<AmountInfo> amountInfos = amountInfoService.list(queryWrapper);
        // 更新状态 给用户余额增加余额
        // 更新状态 给用户余额增加余额
        for (AmountInfo amountInfo : amountInfos) {
            try {
                String planClassId = amountInfo.getPlanClassId();
                if(!StringUtils.isEmpty(planClassId)  &&  StringUtils.isNotEmpty(amountInfo.getUserId())){
                    SysUser user = sysUserMapper.selectUserById(Long.parseLong(amountInfo.getUserId()));
                    BigDecimal totalAmount = user.getAmount().add(amountInfo.getChangeAmount());
                    user.setAmount(totalAmount);
                    sysUserMapper.updateUserAmount(user);
                    // 更新金额明细状态为已生效
                    amountInfo.setValidStatus("1"); // 设置为已生效
                    amountInfoService.updateById(amountInfo);
                }
                // 可以添加日志记录或通知等操作
                System.out.println("用户ID: " + amountInfo.getUserId() + " 的金额已生效，变动金额: " + amountInfo.getChangeAmount());
            } catch (Exception e) {
                // 记录异常，避免一个记录失败影响其他记录处理
                System.err.println("处理用户ID: " + amountInfo.getUserId() + " 的金额生效时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        }

    }


}
